<?php

namespace app\admin\controller\user;
use app\common\library\Sms as Smslib;
use app\common\library\Upload;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\PDOException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                $v->team_name = gettamname($v->team_id);
                $v->top_name =$v->top?'团长':'普通';

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {


        $SexList=Db::name('team')->select();

        $this->assign('SexList',$SexList);

        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function imports()
    {




        $file = $this->request->file('file');
        $upload = new Upload($file);
        $attachment = $upload->upload();

        $file=$attachment->url;


        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        $reader = new Xlsx();


        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];


        //加载文件
        $insert = [];

            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];

            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];


                $inst['nickname']=$values[0];
                $inst['username']=$values[1];
                $inst['mobile']=$values[1];
                $inst['catering']=$values[3];
                $inst['house']=$values[2];
                $inst['team_id']=$values[4];
                $inst['money']=0;
                $inst['status']='normal';
                $inst['email']=$values[1].'@gmail.com';


                $in=Db::name('user')->where('mobile',$values[1])->find();

                if(!$in){
                    Db::name('user')->data($inst)->insert();
                }
            }

        $this->error('导入成功请刷新页面!');



    }



    public function sendmsg(){


        if ($this->request->isPost()){


            $ids=$this->request->request('ids');

            $user=Db::name('user')->where('id','in',$ids)->field('mobile')->select();

            $mobile='';
            foreach ($user as $v){

                $mobile.=$v['mobile'].',';
            }
            $mobile=substr($mobile,0,-1);

            $config = get_addon_config('txsms');
            $template = $this->request->request('template_id');
            $sign = $this->request->post('sign', '');

            $signName = $sign ?: $config['signName'];
            $params = $this->request->post('param');



            $param=[];
            if (!empty($params)){
                $params=explode(',',$params);
                foreach ($params as $k=>$v){
                    $param[$k]=$v;
                }
            }




            $cloudSms = new \addons\txsms\library\TencentCloudSmsClient();
            $ret = $cloudSms->setPhoneNumbers($mobile)
                ->setTemplateId($template)
                ->setSmsSdkAppId($config['smsSdkAppId'])
                ->setSignName($signName)
                ->setTemplateParams($param)
                ->sendSms();



            if (!$ret){
                $this->error('发送失败');
            }

            $this->success('发送成功');



        }
        $ids=$this->request->request('ids');

        $this->view->assign('ids',$ids);



        $templates=Db::name('smsinfo')->select();

        $this->view->assign('templates',$templates);

        return $this->view->fetch();

    }



    public function test(){



        $ids=$this->request->request('ids');

        $user=Db::name('user')->where('id','in',$ids)->field('21,mobile')->select();

        $mobile='';
        foreach ($user as $v){

            $mobile.=$v['mobile'].',';
        }
        $mobile=substr($mobile,0,-1);

        $config = get_addon_config('txsms');
        $template = $this->request->request('template_id')  ;
        $sign = $this->request->post('sign', '');

        $signName = $sign ?: $config['signName'];
        $params = (array)json_decode($this->request->post('param', '', 'trim'));

        $param=[];
        if (!empty($params)){
            $params=explode(',',$params);
            foreach ($params as $k=>$v){
                $param[$k]=$v;
            }
        }

        print_r($param);
        die;

        $cloudSms = new \addons\txsms\library\TencentCloudSmsClient();
        $ret = $cloudSms->setPhoneNumbers($mobile)
            ->setTemplateId($template)
            ->setSmsSdkAppId($config['smsSdkAppId'])
            ->setSignName($signName)
            ->setTemplateParams($param)
            ->sendSms();

        var_dump($ret);


    }



}
